/*
 * @Description: 用户管理
 * @Author: ldx
 * @Date: 2022-09-17 21:22:28
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 23:20:21
 */
import { DownOutlined } from '@ant-design/icons'
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  div,
  Dropdown,
  Form,
  Input,
  Menu,
  Modal,
  Popconfirm,
  Progress,
  Row,
  Select,
  Table,
  Tooltip
} from 'antd'
const { Option } = Select
import moment from 'moment'
import { useState } from 'react'

import {
  deleteUser,
  disableUser,
  enableUser,
  passwordReset,
  queryDetails,
  queryRole,
  queryUesrList,
  registerUser,
  relateRole
} from '@/api/setting/user'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'
import useRsa from '@/hooks/useRsa'
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      offset: 4,
      span: 16
    }
  }
}

const User = () => {
  const [form] = Form.useForm()
  const rasEncrypt = useRsa()
  const [passwordForm] = Form.useForm()
  const [roleForm] = Form.useForm()
  const [addForm] = Form.useForm()
  const [pwd, setPwd] = useState<number>(0) // 密码长度
  const [roleList, setRoleList] = useState<any>([]) // 角色列表
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenRole, setIsModalOpenRole] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [isModalOpenAdd, setIsModalOpenAdd] = useState(false)
  const [user, setUser] = useState<any>({})
  const [details, setDetails] = useState<any>({})

  const handleOk = () => {
    passwordForm.validateFields().then((values: any) => {
      values.password = rasEncrypt(values.password)
      runPasswordReset({ id: user.id, password: values.password })
    })
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  /** 用户分页列表 */
  const { tableProps, search } = useAntdTable(queryUesrList, {
    form
  })
  /** 启用用户 */
  const { runAsync: runEnableUser } = useRequest(enableUser, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 禁用用户 */
  const { runAsync: runDisableUser } = useRequest(disableUser, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 重置密码 */
  const { runAsync: runPasswordReset } = useRequest(passwordReset, {
    manual: true,
    onSuccess: () => {
      setIsModalOpen(false)
    }
  })
  /** 用户删除 */
  const { runAsync: runDeleteUser } = useRequest(deleteUser, {
    manual: true,
    onSuccess: () => {
      search.reset()
    }
  })
  /** 用户关联角色 */
  const { runAsync: runRelateRole } = useRequest(relateRole, {
    manual: true,
    onSuccess: () => {
      setIsModalOpenRole(false)
      search.submit()
    }
  })
  /** 用户详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 角色分页列表 */
  useRequest(queryRole, {
    onSuccess: (res) => {
      setRoleList(res.data)
    }
  })
  /** 注册用户 */
  const { runAsync: runRegisterUser } = useRequest(registerUser, {
    manual: true,
    onSuccess: () => {
      // tableProps.pagination.current = 1
      search.reset()
      setIsModalOpenAdd(false)
    }
  })
  const onPwdChange = (e: any) => {
    console.log(e.target.value as string)
    const password = e.target.value.trim()
    setPwd(() => password.length)
    console.log(pwd)
  }
  const columns: any[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'a',
      width: 100,
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '用户名',
      align: 'center',
      width: 200,
      dataIndex: 'userName'
    },
    {
      title: '登录名',
      align: 'center',
      width: 200,
      dataIndex: 'loginName'
    },
    {
      title: '状态',
      align: 'center',
      width: 100,
      dataIndex: 'status',
      render: (text: number) => {
        return <span>{text === 0 ? '禁用' : '启用'}</span>
      }
    },
    {
      title: '创建时间',
      align: 'center',
      width: 200,
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      width: 200,
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
      width: 300,
      key: 'action',
      align: 'center',
      // fixed: 'right',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            type="link"
            auth={['/**', '/user/**', '/user/details/{id}']}
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <AuthButton
            auth={['/**', '/user/**', '/user/relate-role/{id}']}
            type="link"
            onClick={() => {
              setUser(record)
              setIsModalOpenRole(true)
              roleForm.setFieldsValue({
                roleIds: record.roleIds.map(String)
              })
            }}
          >
            关联角色
          </AuthButton>

          {record.status === 0 ? (
            <AuthButton
              auth={['/**', '/user/**', '/user/status/disable/{id}']}
              onClick={() => runEnableUser(record.id)}
              type="link"
            >
              启用
            </AuthButton>
          ) : (
            <AuthButton
              auth={['/**', '/user/**', '/user/status/enable/{id}']}
              onClick={() => runDisableUser(record.id)}
              type="link"
            >
              禁用
            </AuthButton>
          )}
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="2">
                  <Popconfirm
                    title="确认删除用户?"
                    onConfirm={() => runDeleteUser(record.id)}
                    okText="是"
                    cancelText="否"
                  >
                    <AuthButton
                      auth={['/**', '/user/**', '/user/delete/{id}']}
                      type="link"
                      // className="text-#bd2222"
                    >
                      删除
                    </AuthButton>
                  </Popconfirm>
                </Menu.Item>
                <Menu.Item key="1">
                  <AuthButton
                    auth={['/**', '/user/**', '/user/password-reset']}
                    type="link"
                    onClick={() => {
                      setIsModalOpen(true)
                      setUser(record)
                    }}
                  >
                    重置密码
                  </AuthButton>
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link">
              {' '}
              更多
              <DownOutlined />
            </Button>
          </Dropdown>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  auth={['/**', '/user/**', '/user/create']}
                  onClick={() => setIsModalOpenAdd(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="重置密码"
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={passwordForm}>
          <Tooltip
            placement="right"
            title={
              <>
                <div>
                  <div
                    style={pwd < 6 ? { color: 'red' } : { color: '#72c140' }}
                  >
                    强度：{pwd < 6 ? '太短' : '安全'}
                  </div>
                  <Progress
                    percent={(pwd / 16) * 100}
                    showInfo={false}
                    status={pwd < 6 ? 'exception' : 'success'}
                  />
                </div>
                <span style={{ color: '#5a5a5a' }}>
                  请至少输入 6 个字符。请不要使用容易被猜到的密码。
                </span>
              </>
            }
            trigger="focus"
            color={'white'}
          >
            <Form.Item
              name="password"
              // label="Password"
              rules={[
                {
                  required: true,
                  message: '请输入您的密码!'
                },
                {
                  pattern: /^\S{6,16}$/,
                  message: '请输入6-16位密码,区分大小写'
                }
              ]}
              hasFeedback
            >
              <Input.Password
                placeholder="6-16位密码，区分大小写"
                onChange={onPwdChange}
              />
            </Form.Item>
          </Tooltip>

          <Form.Item
            name="confirm"
            // label="Confirm Password"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '确认您的密码!'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }

                  return Promise.reject(new Error('您两次输入的密码不一致!'))
                }
              })
            ]}
          >
            <Input.Password placeholder="确认密码" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        width={800}
        title="关联角色"
        visible={isModalOpenRole}
        onOk={() => {
          roleForm.validateFields().then((valuse) => {
            runRelateRole(user.id, valuse.roleIds)
          })
        }}
        onCancel={() => {
          setIsModalOpenRole(false)
        }}
      >
        <Form form={roleForm}>
          <Form.Item
            name="roleIds"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              placeholder="请选择角色"
              style={{ width: '100%' }}
              mode="multiple"
            >
              {roleList.map((item: any) => {
                return (
                  <Option key={item.id} value={`${item.id}`}>
                    {item.roleName}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        width={800}
        title="用户详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
        }}
      >
        <div>
          <div>
            <span className="w-120px inline-block mt-10px">用户名：</span>
            <span>{details.userName}</span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">登录名：</span>
            <span>{details.loginName}</span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">创建时间：</span>
            <span>
              {moment(details.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">创建人：</span>
            <span>{details.creatorName}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">角色：</span>
            <span>
              {(details.roles || [])
                .map((role: any) => role.roleName)
                .join('、')}
            </span>
          </div>
        </div>
      </Modal>
      <Modal
        width={800}
        title="添加用户"
        visible={isModalOpenAdd}
        onOk={() => {
          addForm.validateFields().then((values) => {
            values.password = rasEncrypt(values.password)
            runRegisterUser(values)
          })
        }}
        onCancel={() => {
          setIsModalOpenAdd(false)
        }}
      >
        <div>
          <Form
            {...formItemLayout}
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            scrollToFirstError
          >
            <Form.Item
              name="userName"
              // label="Nickname"
              // tooltip="What do you want others to call you?"
              rules={[
                {
                  required: true,
                  message: '请输入您的姓名!',
                  whitespace: true
                }
                // {
                //   pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
                //   message: '请输入2-30个中文字符'
                // }
              ]}
            >
              <Input placeholder="您的姓名，2-30个字符，必填" />
            </Form.Item>
            <Form.Item
              name="loginName"
              // label="Phone Number"
              rules={[
                {
                  required: true,
                  message: '请输入账号!'
                }
                // {
                //   pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, //正则校验手机号
                //   message: '请输入正确的手机号'
                // }
              ]}
            >
              <Input
                placeholder="请输入账号"
                style={{
                  width: '100%'
                }}
              />
            </Form.Item>

            <Tooltip
              placement="right"
              title={
                <>
                  <div>
                    <div
                      style={pwd < 6 ? { color: 'red' } : { color: '#72c140' }}
                    >
                      强度：{pwd < 6 ? '太短' : '安全'}
                    </div>
                    <Progress
                      percent={(pwd / 16) * 100}
                      showInfo={false}
                      status={pwd < 6 ? 'exception' : 'success'}
                    />
                  </div>
                  <span style={{ color: '#5a5a5a' }}>
                    请至少输入 6 个字符。请不要使用容易被猜到的密码。
                  </span>
                </>
              }
              trigger="focus"
              color={'white'}
            >
              <Form.Item
                name="password"
                // label="Password"
                rules={[
                  {
                    required: true,
                    message: '请输入您的密码!'
                  },
                  {
                    pattern: /^\S{6,16}$/,
                    message: '请输入6-16位密码,区分大小写'
                  }
                ]}
                hasFeedback
              >
                <Input.Password
                  placeholder="6-16位密码，区分大小写"
                  onChange={onPwdChange}
                />
              </Form.Item>
            </Tooltip>

            <Form.Item
              name="confirm"
              // label="Confirm Password"
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '确认您的密码!'
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve()
                    }

                    return Promise.reject(new Error('您两次输入的密码不一致!'))
                  }
                })
              ]}
            >
              <Input.Password placeholder="确认密码" />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default User
